package com.run.runbbs.controller;

import com.run.runbbs.Event.EventProducer;
import com.run.runbbs.common.dto.CommentDto;
import com.run.runbbs.common.lang.Result;
import com.run.runbbs.entity.Comment;
import com.run.runbbs.entity.Event;
import com.run.runbbs.entity.Post;
import com.run.runbbs.entity.User;
import com.run.runbbs.service.impl.CommentService;
import com.run.runbbs.service.impl.PostService;
import com.run.runbbs.service.impl.UserService;
import com.run.runbbs.util.Constant;
import com.run.runbbs.util.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class CommentController implements Constant {
    @Autowired
    private CommentService commentService;
    @Autowired
    private UserService userService;
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private PostService postService;
    @Autowired
    private JwtUtils jwtUtils;



//    @RequiresAuthentication
    @GetMapping("/getComment")
    public Result getComment(int postId, int offset){
        List<Comment> commentList=commentService.findCommentsByEntity(ENTITY_TYPE_POST,postId,offset,10);
        List<Map<String,Object>> commentVoList=new ArrayList<>();
        if(commentList!=null){
            for(Comment comment : commentList){
                Map<String,Object> commentVo=new HashMap<>();
                Map<String,Object> simpleComment=new HashMap<>();
                //没用的数据不传
                simpleComment.put("id",comment.getId());
                simpleComment.put("content",comment.getContent());
                simpleComment.put("createTime",comment.getCreateTime());
                commentVo.put("comment",simpleComment);
                commentVo.put("user",userService.findSimpleUserById(comment.getUserId()));

                //评论中的回复
                List<Comment> replyList=commentService.findCommentsByEntity(ENTITY_TYPE_COMMENT,comment.getId(),0,Integer.MAX_VALUE);
                List<Map<String,Object>> replyVoList=new ArrayList<>();
                if(replyList!=null){
                    for(Comment reply : replyList){
                        Map<String,Object> replyVo=new HashMap<>();
                        Map<String,Object> simpleReply=new HashMap<>();
                        //没用的数据不传
                        simpleReply.put("id",reply.getId());
                        simpleReply.put("content",reply.getContent());
                        simpleReply.put("createTime",reply.getCreateTime());
                        replyVo.put("reply",simpleReply);
                        replyVo.put("user",userService.findSimpleUserById(reply.getUserId()));
                        //回复的目标
                        User target=reply.getTargetId()==0?null:userService.findSimpleUserById(reply.getTargetId());
                        replyVo.put("target",target);

                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys",replyVoList);

                //回复的数量
                int replyCount=commentService.findCommentCount(ENTITY_TYPE_COMMENT,comment.getId());
                commentVo.put("replyCount",replyCount);

                commentVoList.add(commentVo);
            }
        }
        return Result.success(commentVoList);
    }

    @PostMapping("/addComment")
    public Result addComment(@Validated @RequestBody CommentDto commentDto, HttpServletRequest request){
        int userId=jwtUtils.getUserId(request);

        Comment comment=new Comment();
        //复制对应的属性,将commentDto的值复制到comment中去
        BeanUtils.copyProperties(commentDto,comment);
        comment.setCreateTime(new Date());
        comment.setStatus(0);
        //存入数据库
        commentService.addComment(comment);
        //返回评论
        Map<String,Object> simpleComment=new HashMap<>();
        //没用的数据不传
        simpleComment.put("id",comment.getId());
        simpleComment.put("content",comment.getContent());
        simpleComment.put("createTime",comment.getCreateTime());
        //触发评论事件（消息通知）
        //不过是评论的是帖子还是评论，都要把postId设置进去。因为显示通知信息的时候都是谁谁谁评论了你的啥帖子
        //设置EntityUserId 是为了知道通知要发给谁。
        Event event=new Event()
                .setTopic(TOPIC_COMMENT)
                .setUserId(comment.getUserId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId",commentDto.getPostId()).setData("commentId",comment.getId());
        if(comment.getEntityType()==ENTITY_TYPE_POST){
            Post target=postService.findPost(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }else if(comment.getEntityType()==ENTITY_TYPE_COMMENT){
            Comment target=commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        if(event.getEntityUserId()!=userId){
            eventProducer.fireEvent(event);
        }
        //触发事件（修改的帖子的评论数量同步到es服务器）
        if(comment.getEntityType()==ENTITY_TYPE_POST){
            event=new Event()
                    .setTopic(TOPIC_UPDATE)
                    .setUserId(comment.getUserId())
                    .setEntityId(ENTITY_TYPE_POST)
                    .setEntityId(commentDto.getPostId());
            eventProducer.fireEvent(event);
        }
        return Result.success(simpleComment);

    }
}
